package com.pp.controller;


import com.pp.bean.PpImage;
import com.pp.bean.UploadData;
import com.pp.bean.UploadResult;
import com.pp.service.IPpImageService;
import com.pp.util.upload.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张子艺
 * @since 2019-03-13
 */
@Controller
@RequestMapping("/ppImage")
public class PpImageController {
    @Autowired
    IPpImageService ppImageService;
    /**
     *  轮播图片
     *
     * @return
     */
    @RequestMapping(value = "/findImage", method = RequestMethod.GET)
    public String findImage(Model model)  {

        return "updateImage";
    }
    //path 为图片在服务器的绝对路径

    @RequestMapping("/getPhoto")
    public   void getPhoto(HttpServletResponse response, @RequestParam("path") String path) throws IOException {
        try {
            File file = new File(path);
            FileInputStream fis =  new FileInputStream(file);
            OutputStream out = response.getOutputStream();
            long size = file.length();
            byte[] temp = new byte[(int) size];
            fis.read(temp, 0, (int) size);
            byte[] data = temp;
            response.setContentType("image/png");
            fis.close();
            out.write(data);
            out.flush();
        }catch (IOException c){
        }

    }

    /**
     *  轮播图片新增
     *
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public UploadResult saveNewImage(@RequestParam("file") MultipartFile file)  {
        try {
            UploadResult result=new UploadResult();
            result.setData(new UploadData(UploadFile.fileUpload(file)));
            result.setMsg("上传成功");
            result.setCode(0);
            PpImage ppImage=new PpImage();
            ppImage.setPpImageUrl(result.getData().getSrc());
            ppImageService.save(ppImage);
            return result;
        } catch (Exception e) {
            return new UploadResult();
        }

    }
    /**
     *  轮播图片新增
     *
     * @return
     */
    @RequestMapping(value = "/delImage" )
    @ResponseBody
    public boolean delImage(Long id,String ppImageUrl)  {
        if(UploadFile.delFile(ppImageUrl)){
            ppImageService.removeById(id);
            return true;
        }
        return false;
        }

}
